<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2019/3/25
 * Time: 11:30
 */
namespace App\Services\RepaymentPay;

class RepaymentPayService
{
    protected $apiUrl;
    protected $mchId;
    protected $appId;
    protected $apiKey;
    protected $tradeNotifyUrl;

    public function __construct()
    {
        $this->apiUrl = config('pay.fourpay.api_url');
        $this->mchId = config('pay.fourpay.mch_id');
        $this->appId = config('pay.fourpay.app_id');
        $this->apiKey = config('pay.fourpay.api_key');
        $this->tradeNotifyUrl = config('pay.fourpay.receive_and_payment_g.trade_notify_url');
    }

    /**
     * 获取接口请求结果
     * @param $param
     * @param $url
     * @return mixed
     */
    protected function getRequestResult($param, $url)
    {
        $param['sign'] = getSign($param, $this->apiKey);
        $client = new \GuzzleHttp\Client(['verify' => false]);
        $response = $client->request('post', $url, ['form_params' => $param]);
        $json = $response->getBody()->getContents();
        $result = json_decode($json, true);
        return [
            'params' => $param,
            'response' => $result
        ];
    }

    /**
     * 代付
     * @param $tradeNo
     * @param $realname
     * @param $bankCardNo
     * @param $amount
     * @return mixed
     */
    public function trade($tradeNo, $realname, $bankCardNo, $amount)
    {
        $param['mch_id'] = $this->mchId;
        $param['app_id'] = $this->appId;
        $param['mch_no'] = $tradeNo;
        $param['realname'] = $realname;
        $param['bank_card_no'] = $bankCardNo;
        $param['amount'] = (string)round($amount * 100, 2);
        $param['account_type'] = 'bank_card';
        $param['account_property'] = 'private';
        $param['notify_url'] = $this->tradeNotifyUrl;
        $url = $this->apiUrl . 'api/pay/receive_and_payment_g/payment';
        return $this->getRequestResult($param, $url);
    }
}
